/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.google.cse.emea.universaltransformer.transformers;

import com.google.cse.emea.universaltransformer.editors.*;
import com.google.cse.emea.jct.utils.Profile;
import java.util.Collection;
import java.util.HashMap;
import java.util.ServiceLoader;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author jtrapp
 */
public class TransformerFactory {

    private static ServiceLoader<TransformerModule> transformerLoader =
            ServiceLoader.load(TransformerModule.class);


    private HashMap<String, String> transformerNames;
    private HashMap<String, TransformerModule> transformerList;
    private static TransformerFactory instance = null;

    /**
     * The Factory
     */
    public static TransformerFactory getFactory() {
        if (instance == null) {
            instance = new TransformerFactory();
        }
        return instance;
    }

    private TransformerFactory() {
        transformerNames = new HashMap<String, String>();
        transformerList = new HashMap<String, TransformerModule>();
        
        /** Add all inputPanels to the card panel.*/
        for (TransformerModule transformer : transformerLoader) {
            String[] names = transformer.getName().split(",");
            for (String name : names) {
                transformerList.put(name, transformer);
            }
        }
    }
    
    public Collection<TransformerModule> getTransformers() {
        return transformerList.values();
    }

    /**
     * Get an Editor for a mime type
     * @param type Mime Type
     * @return The editor, that is able to display that type.
     */
    public static TransformerModule getTransformer(String type) {

        return getFactory().transformerList.get(type);
    }

    public TransformerModule getTransformer(Profile profile, String key, String type) {
        try {
            if (transformerNames == null) {
                transformerNames = profile.loadTable(key);
            }
            String classname = transformerNames.get(type);

            TransformerModule editor = transformerList.get(classname);
            if (editor == null) {
                editor = (TransformerModule) Class.forName(classname).newInstance();
                transformerList.put(classname, editor);
            }

            return editor;
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(TransformerFactory.class.getName()).log(Level.SEVERE, "Could not find editor for " + type, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(TransformerFactory.class.getName()).log(Level.SEVERE, "Can't instantiate editor for " + type, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(TransformerFactory.class.getName()).log(Level.SEVERE, "Illegal access for editor for " + type, ex);
        }
        return null;
    }
}
